package com.base.simple.utils;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Description: TODO
 *
 * @author: Wang
 * @date: 2017/11/29 15:26
 * email:life_artist@163.com
 * Copyright©2017 by wang. All rights reserved.
 */

public class ThreadUtil<T> {

    private Executor<T> executor;

    private ResultListener<T> resultListener;

    public static <T> ThreadUtil<T> getThread(Class<T> clazz) {
        return new ThreadUtil<T>();
    }

    private ThreadUtil() {

    }

    /**
     * 需要放入线程中执行的方法
     *
     * @param executor
     * @return
     */
    public ThreadUtil<T> setExecutor(Executor<T> executor) {
        this.executor = executor;
        return this;
    }

    /**
     * 回掉到主线程的结果
     *
     * @param resultListener
     * @return
     */
    public ThreadUtil<T> setResultListener(ResultListener<T> resultListener) {
        this.resultListener = resultListener;
        return this;
    }

    public void execute() {

        if (executor == null) {
            return;
        }

        if (resultListener == null) {
            return;
        }

        Observable
                .create(new ObservableOnSubscribe<T>() {
                    @Override
                    public void subscribe(ObservableEmitter<T> emitter) throws Exception {
                        emitter.onNext(executor.onExe());
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<T>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(T value) {
                        resultListener.onResult(true, value, null);
                    }

                    @Override
                    public void onError(Throwable e) {
                        resultListener.onResult(false, null, e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }


    public interface Executor<T> {

        /**
         * 执行方法
         *
         * @return
         */
        T onExe();
    }

    public interface ResultListener<T> {

        /**
         * 返回结果
         *
         * @param isSuccess
         * @param t
         * @param message
         */
        void onResult(boolean isSuccess, T t, String message);

    }
}
